#include "writer.h"
#include <QDebug>
#include "randomgenerator.h"

Writer::Writer(int writeInterval, QObject* parent) :
    interval(writeInterval), QObject(parent), QRunnable()
{
    myBooks.reserve(shelf::books.capacity());
}

void Writer::tryEdit(size_t index)
{
    emit changePeopleCount(-1);
    while (!shelf::books[index]){}
    shelf::abilityToChange.lock();
    shelf::books[index] = false;
    shelf::abilityToChange.unlock();
    emit changePeopleCount(1);
    qDebug() << "edit " << index << " " << shelf::books.size();
    sleep(interval);
    shelf::abilityToChange.lock();
    shelf::books[index] = true;
    emit changedBooksCount(1);
    shelf::abilityToChange.unlock();
    qDebug() << "editor puts  " << index;
}

void Writer::tryWrite()
{
    shelf::abilityToChange.lock();
    int shelfSize = shelf::books.size() ;
    int maxShelfSize = shelf::books.capacity();
    shelf::abilityToChange.unlock();
    if(shelfSize >= maxShelfSize)
    {
        return;
    }
    shelf::abilityToChange.lock();
    shelf::books.push_back(false);
    myBooks.push_back(shelf::books.size() - 1);
    shelf::abilityToChange.unlock();
    sleep(interval);
    shelf::abilityToChange.lock();
    shelf::books[shelf::books.size() - 1] = true;
    shelf::abilityToChange.unlock();
    emit changedBooksCount(1);

    qDebug() << "writer puts the book";
}

void Writer::run()
{
    while (true)
    {
        int booksSize = myBooks.size();
        shelf::abilityToChange.lock();
        int shelfSize = shelf::books.size() ;
        int maxShelfSize = shelf::books.capacity();
        shelf::abilityToChange.unlock();
        if (shelfSize < maxShelfSize && qrand() % 2 == 0)
        {
            tryWrite();
            continue;
        }
        else if (booksSize > 0)
        {
            int book = qrand() % booksSize;
            qDebug() << "book " << book << " " << booksSize;
            size_t curBook = myBooks.at(book);
            qDebug() << "tryEdit " << curBook;
            tryEdit(curBook);
        }
    }
}
